<?php

class CatalogController extends Controller
{
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);

		$catalogs = Catalog::model()->findAll('parent = '.$model->id);
		foreach($catalogs as &$catalog){
			$catalogItems = CatalogItem::model()->findAll(array('limit'=>3, 'order'=>'view_count DESC', 'condition'=>'catalog_id=:x AND state=:state', 'params'=>array(':x'=>$catalog->id, ':state'=>ConstProductState::Publicated)));
			$catalog->catalogItems = $catalogItems;
		}

		$model['catalogs'] = $catalogs;

		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$catalogs = Catalog::model()->findAll();

		foreach($catalogs as &$catalog){
			$catalogItems = CatalogItem::model()->findAll(array('limit'=>4, 'order'=>'view_count DESC', 'condition'=>'catalog_id=:x AND state=:state', 'params'=>array(':x'=>$catalog->id, ':state'=>ConstProductState::Publicated)));
			if(count($catalogItems)>0){
				$catalog->catalogItems = $catalogItems;
			}
		}

		$this->render('index',array(
			'model'=>$catalogs,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Catalog the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Catalog::model()->with('pictures')->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Catalog $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='catalog-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
